<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      title="关键词列表"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button v-auth="'/keywords/add'" type="primary" :icon="CirclePlus" @click="openDrawer('新增')">
          新增关键词
        </el-button>
        <el-button type="danger" :icon="Delete" plain :disabled="!scope.isSelected" @click="batchDelete(scope.selectedListIds)">
          批量删除
        </el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- cover -->
      <template #banner="scope">
        <el-image :src="scope.row.banner" style="height: 65px;" :preview-src-list="[scope.row.banner]" preview-teleported fit="cover" />
      </template>
      <!-- icon_name -->
      <template #icon_name="scope">
        <el-icon v-if="scope.row.icon_name && scope.row.icon_type == 1" style="font-size: 18px">
          <component :is="scope.row.icon_name"></component>
        </el-icon>
        <i v-if="scope.row.icon_name && scope.row.icon_type == 2" class="el-icon iconfont" :class="scope.row.icon_name" />
      </template>
      <!-- status -->
      <template #status="scope">
        <el-switch
          :model-value="scope.row.status"
          active-text="启用"
          inactive-text="禁用"
          inline-prompt
          :active-value="1"
          :inactive-value="0"
          :disabled="!authButton('/keywords/change_status/*')"
          @click="changeStatus(scope.row)"
        />
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" v-auth="'/keywords/edit/*'" @click="openDrawer('编辑', scope.row)"
          >编辑</el-button
        >
        <el-button type="danger" link :icon="Delete" v-auth="'/keywords/delete/*'" @click="delKeywords(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <KeywordsDrawer ref="drawerRef" />
  </div>
</template>

<script lang="ts">
export default {
  name: "keywordsManage",
};
</script>

<script setup lang="ts">
import { CirclePlus, Delete, EditPen, View } from "@element-plus/icons-vue";
import KeywordsDrawer from "@/views/app/keywords/KeywordsDrawer.vue";
import ProTable from "@/components/ProTable/index.vue";
import { reactive, ref } from "vue";
import { keywords } from "./keywords.tsx";
import { ProTableInstance } from "@/components/ProTable/interface";
import {
  addKeywordsApi,
  changeStatusApi,
  keywordsPageListApi,
  deleteKeywordsByIdApi,
  deleteKeywordsApi,
  editKeywordsApi,
  changeSortApi,
} from "@/api/modules/keywords";
import { useHandleData } from "@/hooks/useHandleData";
import { authButton } from "@/hooks/useAuthButton";
import { Recordable } from "@/interface/types.ts";

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});

const { columns } = keywords();

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.create_time && (newParams.startTime = newParams.create_time[0]);
  newParams.create_time && (newParams.endTime = newParams.create_time[1]);
  delete newParams.create_time;
  return keywordsPageListApi(newParams);
};

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    rows: data.rows,
    total: data.total,
    page_num: data.page_num,
    page_size: data.page_size
  };
};

// 打开 dialog(新增、查看、编辑)
const drawerRef = ref();
const openDrawer = (title: string, rowData: Partial<Recordable> = {}) => {
  console.log(rowData);
  let params = {
    title,
    rowData: { ...rowData },
    isView: title === "查看",
    api: title === "新增" ? addKeywordsApi : title === "编辑" ? editKeywordsApi : "",
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value.acceptParams(params);
};

// 删除关键词信息
const delKeywords = async (row: Recordable) => {
  await useHandleData(deleteKeywordsByIdApi, row.id, `删除【${row.name}】关键词`);
  proTable.value?.getTableList();
};

// 批量删除关键词信息
const batchDelete = async (pds: string[]) => {
  await useHandleData(deleteKeywordsApi, { pds }, "删除所选关键词信息");
  proTable.value?.clearSelection();
  proTable.value?.getTableList();
};

// 切换状态
const changeStatus = async (row: Recordable) => {
  if (!authButton("/keywords/change_status/*")) {
    return;
  }
  await useHandleData(changeStatusApi, row.id, `切换【${row.name}】关键词状态`);
  proTable.value?.getTableList();
};
</script>

<style lang="scss" scoped></style>
